package ip181

import (
	"encoding/json"
	"fmt"
	"github.com/ruoklive/proxypool/internal/ipgetter/base"
	"github.com/ruoklive/proxypool/pkg/models"
	"github.com/ruoklive/proxypool/pkg/register"
	"go.uber.org/zap"
	"io"
	"io/ioutil"
)

func init() {
	register.Add(func() register.IPGetter {
		return New()
	})
}

type ip181 struct {
	ErrorCode string   `json:"ERRORCODE"`
	Results   []Result `json:"RESULT"`
}

// Result struct
type Result struct {
	Position string `json:"position"`
	Port     string `json:"port"`
	IP       string `json:"ip"`
}

type IPGetter struct {
	base.Base
}

func New() *IPGetter {
	g := &IPGetter{}
	g.Base = base.NewBase("http://www.ip181.com/",g.Parse,"IP181")
	return g
}

// IP181 get ip from ip181.com
func (g *IPGetter) Parse(reader io.ReadCloser) (result []*models.IP) {
	var ips ip181
	var results []Result

	body, _ := ioutil.ReadAll(reader)

	err := json.Unmarshal(body, &ips)

	if err != nil {
		fmt.Println(err)
	}

	results = ips.Results

	for i := 0; i < len(results); i++ {
		ip := models.NewIP()
		ip.Data = results[i].IP + ":" + results[i].Port
		ip.Type1 = "http"
		g.Info("GET IP", zap.String("ip",ip.String()))
		result = append(result, ip)
	}

	g.Info("done.")
	return
}
